package com.david.func_test.activity

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.View.OnClickListener
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.bumptech.glide.request.FutureTarget
import com.david.func_test.R
import com.david.core.utils.downLoadImgs
import com.david.http.http.util.combineResultTriple
import com.david.http.http.util.zipResultPair
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.launch


//参考链接：https://juejin.cn/post/6978829247917850654
class FlowTestActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_flow_test)

        findViewById<View>(R.id.flow_start).setOnClickListener(object : OnClickListener {
            override fun onClick(v: View?) {
                //val pm = packageManager
                //val apps = pm.getInstalledApplications(0)
                //
                //for (app in apps) {
                //    Log.v("PackageName", app.packageName)
                //}

                //zipTest()
                //combineTest()
                //zip3Test()
                downImages()
            }
        })
        //findViewById<View>(R.id.flow_stop).setOnClickListener {  }

    }

    fun zipTest() {
        lifecycleScope.launch {
            val flow1 = flowOf(1, 2, 3)
            val flow2 = arrayListOf("a", "b", "c").asFlow()
            flow2.zipResultPair(flow1).collect {
                Log.e("flow", "collectLatest: $it")
            }
        }
    }

    fun zip3Test() {
        lifecycleScope.launch {
            val flow1 = flow {
                Log.e("flow", "flow1 start...")
                kotlinx.coroutines.delay(1000)
                emit(1)
            }
            val flow2 = flow {
                Log.e("flow", "flow2 start...")
                emit("one")
            }

            val flow3 = flow {
                Log.e("flow", "flow3 start...")
                kotlinx.coroutines.delay(2000)
                emit("a")
            }

            flow1.combineResultTriple(flow2, flow3).collectLatest {
                Log.e("flow", "collectLatest: $it")
            }

            //
            //flow2.zip(flow1) { one, two ->
            //    Log.e("flow", "collectLatest first zip:" + "$one, $two")
            //
            //    "$one, $two"
            //}.zip(flow3){ resule, three ->
            //    Log.e("flow", "collectLatest second zip:" + "$resule, $three")
            //
            //    "$resule, $three"
            //}.collect {
            //    Log.e("flow", "collectLatest: $it")
            //}
        }
    }

    fun combineTest() {
        lifecycleScope.launch {
            val flow1 = flowOf(1, 2, 3)
            val flow2 = arrayListOf("a", "b", "c").asFlow()

            flow2.combine(flow1) { one, two ->
                "$one, $two"
            }.collect {
                Log.e("flow", "collectLatest: $it")
            }


            val flow3 = listOf(1, 2, 3).asFlow()
            val flow4 = listOf(1, 2, 3).asFlow()
            val flow5 = listOf(1, 2, 3).asFlow()
            val flow6 = listOf(1, 2, 3).asFlow()
            val flow7 = listOf(1, 2, 3).asFlow()

            combine(flow1, flow2, flow3, flow4, flow5) { one, two, three, four ,five ->
                arrayOf(one, two, three, four, five)
            }.collectLatest {

            }
            //超过5个则会调用变长变量方法
            combine(flow1, flow2, flow3, flow4, flow5, flow6) { items ->
                items
            }.collectLatest {

            }
        }
    }

    fun downImages() {
        downLoadImgs(arrayListOf("xxx","https://profile-avatar.csdnimg.cn/5fd3878c7ee8446db24a65101b08a1f7_chuyouyinghe.jpg!1","https://profile-avatar.csdnimg.cn/9f0feb29f9474770ae1676c328b223bf_u011897062.jpg!1", "https://profile-avatar.csdnimg.cn/6f08b380877c432fb0fe10e322b717c3_wzj_what_why_how.jpg!1"), this) {
            findViewById<ImageView>(R.id.img1).post {
                findViewById<ImageView>(R.id.img1).setImageBitmap(it[0])
                findViewById<ImageView>(R.id.img2).setImageBitmap(it[1])
            }
        }

        //CoroutineScope(Dispatchers.IO).launch {
        //    //参考链接：https://blog.csdn.net/chuyouyinghe/article/details/134538741
        //    val imageUrls: List<String> = arrayListOf("https://profile-avatar.csdnimg.cn/9f0feb29f9474770ae1676c328b223bf_u011897062.jpg!1", "https://profile-avatar.csdnimg.cn/6f08b380877c432fb0fe10e322b717c3_wzj_what_why_how.jpg!1")
        //    flow {
        //        val deferredImages: List<Deferred<Bitmap?>> = imageUrls.map { url ->
        //            async {
        //                BitmapFactory.decodeFile(Glide.with(applicationContext)
        //                    .asFile()
        //                    .load(url)
        //                    .submit(FutureTarget.SIZE_ORIGINAL, FutureTarget.SIZE_ORIGINAL)
        //                    .get().path)
        //            }
        //        }
        //        val images = deferredImages.awaitAll()
        //        emit(images)
        //
        //        //emit(listOf<Bitmap>())
        //    }.collect{
        //        Log.e("TAG", "downImages: ")
        //        //findViewById<ImageView>(R.id.img1).post {
        //            findViewById<ImageView>(R.id.img1).setImageBitmap(it[0])
        //            findViewById<ImageView>(R.id.img2).setImageBitmap(it[1])
        //        //}
        //
        //    }
        //
        //    //flow {
        //        //val future: FutureTarget<File> = Glide.with(applicationContext)
        //        //    .load("https://profile-avatar.csdnimg.cn/6f08b380877c432fb0fe10e322b717c3_wzj_what_why_how.jpg!1")
        //        //    .downloadOnly(500, 500)
        //        //val cacheFile = future.get()
        //        //emit(cacheFile)
        //
        //    //    emit(downloadImage(applicationContext, "https://profile-avatar.csdnimg.cn/6f08b380877c432fb0fe10e322b717c3_wzj_what_why_how.jpg!1"))
        //    //}.flowOn(Dispatchers.IO).collect {
        //    //    Log.e("TAG", "downImages: ${it}")
        //    //}
        //}
    }

    suspend fun downloadImage(context: Context?, url: String?): Bitmap? {
        return BitmapFactory.decodeFile(Glide.with(context!!)
            .asFile()
            .load(url)
            .submit(FutureTarget.SIZE_ORIGINAL, FutureTarget.SIZE_ORIGINAL)
            .get().path)
        //RequestBuilder(File.class::java, future).apply(DOWNLOAD_ONLY_OPTIONS)
        //try {
        //    return future.get() // wait for resource ready
        //} catch (e: InterruptedException) {
        //    e.printStackTrace()
        //} catch (e: ExecutionException) {
        //    e.printStackTrace()
        //}
        //return null
    }

}